<template>
  <div class="listings-page">
    <!-- 搜索表单 -->
    <el-card class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="信息类型">
          <el-select v-model="searchForm.listing_type" placeholder="请选择类型" clearable>
            <el-option label="公司" value="公司" />
            <el-option label="个体户" value="个体户" />
            <el-option label="代账户" value="代账户" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="在售" value="在售" />
            <el-option label="已售" value="已售" />
            <el-option label="下架" value="下架" />
          </el-select>
        </el-form-item>

        <el-form-item label="搜索关键词">
          <el-input
            v-model="searchForm.search"
            placeholder="请输入公司名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 挂牌信息列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>挂牌信息列表</span>
          <div class="header-actions">
            <el-button @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="listingList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column prop="company_name" label="公司名称" min-width="200" />

        <el-table-column label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.listing_type)">
              {{ row.listing_type }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="价格" width="120">
          <template #default="{ row }">
            <span v-if="row.is_negotiable">面议</span>
            <span v-else-if="row.price">¥{{ row.price.toLocaleString() }}</span>
            <span v-else>未设置</span>
          </template>
        </el-table-column>

        <el-table-column prop="registration_city" label="注册地" width="120" />

        <el-table-column label="发布者手机号" width="130">
          <template #default="{ row }">
            <span v-if="row.user?.phone_number" class="phone-number">
              {{ row.user.phone_number }}
            </span>
            <span v-else class="no-phone">未填写</span>
          </template>
        </el-table-column>

        <el-table-column label="发布时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                type="primary"
                size="small"
                @click="handleViewDetail(row)"
              >
                查看详情
              </el-button>

              <el-dropdown @command="(command: string) => handleStatusChange(row, command)">
                <el-button type="warning" size="small">
                  审核操作
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="在售" :disabled="row.status === '在售'">
                      设为在售
                    </el-dropdown-item>
                    <el-dropdown-item command="下架" :disabled="row.status === '下架'">
                      下架
                    </el-dropdown-item>
                    <el-dropdown-item command="已售" :disabled="row.status === '已售'">
                      标记已售
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>

              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="挂牌信息详情"
      width="800px"
      :before-close="handleCloseDetail"
    >
      <div v-if="currentListing" class="listing-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="信息ID">
            {{ currentListing.id }}
          </el-descriptions-item>
          <el-descriptions-item label="公司名称">
            {{ currentListing.company_name }}
          </el-descriptions-item>
          <el-descriptions-item label="信息类型">
            <el-tag :type="getTypeTagType(currentListing.listing_type)">
              {{ currentListing.listing_type }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentListing.status)">
              {{ currentListing.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="价格">
            <span v-if="currentListing.is_negotiable">面议</span>
            <span v-else-if="currentListing.price">¥{{ currentListing.price.toLocaleString() }}</span>
            <span v-else>未设置</span>
          </el-descriptions-item>
          <el-descriptions-item label="注册地">
            {{ currentListing.registration_province }} {{ currentListing.registration_city }}
          </el-descriptions-item>
          <el-descriptions-item label="成立日期">
            {{ currentListing.establishment_date || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="注册资本">
            {{ currentListing.registered_capital_range || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="实缴状态">
            {{ currentListing.paid_in_status || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="公司类型">
            {{ currentListing.company_type || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="税务情况">
            {{ currentListing.tax_status || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="纳税等级">
            {{ currentListing.tax_grade || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="银行账户">
            {{ currentListing.bank_account_status || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="银行流水">
            {{ currentListing.bank_flow || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="发布者手机号">
            <span v-if="currentListing.user?.phone_number" class="phone-number">
              {{ currentListing.user.phone_number }}
            </span>
            <span v-else class="no-phone">未填写</span>
          </el-descriptions-item>
          <el-descriptions-item label="发布时间">
            {{ formatDate(currentListing.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDate(currentListing.updated_at) }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 特殊资质 -->
        <div class="qualifications">
          <h4>特殊资质</h4>
          <el-tag v-if="currentListing.has_trademark" type="success" class="qualification-tag">
            有商标
          </el-tag>
          <el-tag v-if="currentListing.has_patent" type="success" class="qualification-tag">
            有专利
          </el-tag>
          <el-tag v-if="currentListing.has_software_copyright" type="success" class="qualification-tag">
            有软著
          </el-tag>
          <el-tag v-if="currentListing.has_license_plate" type="success" class="qualification-tag">
            有车牌指标
          </el-tag>
          <el-tag v-if="currentListing.has_social_security" type="success" class="qualification-tag">
            有社保记录
          </el-tag>
          <el-tag v-if="currentListing.has_bidding_history" type="success" class="qualification-tag">
            有招投标业绩
          </el-tag>
          <span v-if="!hasAnyQualification(currentListing)" class="no-qualification">
            无特殊资质
          </span>
        </div>

        <!-- 详细描述 -->
        <div v-if="currentListing.description" class="description">
          <h4>详细描述</h4>
          <p>{{ currentListing.description }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, ArrowDown } from '@element-plus/icons-vue'
import { listingApi, type Listing, type ListingListParams } from '@/api/admin'

// 响应式数据
const loading = ref(false)
const listingList = ref<Listing[]>([])
const detailDialogVisible = ref(false)
const currentListing = ref<Listing | null>(null)

// 搜索表单
const searchForm = reactive<ListingListParams>({
  listing_type: undefined,
  status: '', // 默认显示所有状态
  search: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString()
}

// 获取类型标签颜色
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    '公司': 'primary',
    '个体户': 'success',
    '代账户': 'warning'
  }
  return typeMap[type] || ''
}

// 获取状态标签颜色
const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    '在售': 'success',
    '已售': 'info',
    '下架': 'danger'
  }
  return statusMap[status] || ''
}

// 检查是否有特殊资质
const hasAnyQualification = (listing: Listing) => {
  return listing.has_trademark ||
         listing.has_patent ||
         listing.has_software_copyright ||
         listing.has_license_plate ||
         listing.has_social_security ||
         listing.has_bidding_history
}

// 获取挂牌信息列表
const getListingList = async () => {
  loading.value = true
  try {
    const params: ListingListParams = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }

    const response = await listingApi.getList(params)
    listingList.value = response.data
    pagination.total = response.pagination.total
  } catch (error) {
    console.error('获取挂牌信息列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getListingList()
}

// 重置搜索
const handleReset = () => {
  searchForm.listing_type = undefined
  searchForm.status = '' // 重置为显示所有状态
  searchForm.search = ''
  pagination.page = 1
  getListingList()
}

// 刷新
const handleRefresh = () => {
  getListingList()
}

// 查看详情
const handleViewDetail = async (listing: Listing) => {
  try {
    const response = await listingApi.getDetail(listing.id)
    currentListing.value = response.data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取挂牌信息详情失败:', error)
  }
}

// 关闭详情对话框
const handleCloseDetail = () => {
  detailDialogVisible.value = false
  currentListing.value = null
}

// 状态变更
const handleStatusChange = async (listing: Listing, status: string) => {
  try {
    const statusText = status === '在售' ? '上架' : status === '下架' ? '下架' : '标记为已售'
    await ElMessageBox.confirm(`确定要${statusText}信息 "${listing.company_name}" 吗？`, `确认${statusText}`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await listingApi.updateStatus(listing.id, status as any)
    ElMessage.success(`${statusText}成功`)
    getListingList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('状态变更失败:', error)
    }
  }
}

// 删除
const handleDelete = async (listing: Listing) => {
  try {
    await ElMessageBox.confirm(`确定要删除信息 "${listing.company_name}" 吗？此操作不可恢复！`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })

    await listingApi.delete(listing.id)
    ElMessage.success('删除成功')
    getListingList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  getListingList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page
  getListingList()
}

// 初始化
onMounted(() => {
  getListingList()
})
</script>

<style scoped>
.listings-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.listing-detail {
  padding: 20px 0;
}

.qualifications {
  margin-top: 20px;
}

.qualifications h4 {
  margin-bottom: 10px;
  color: #303133;
}

.qualification-tag {
  margin-right: 8px;
  margin-bottom: 5px;
}

.no-qualification {
  color: #909399;
  font-style: italic;
}

.description {
  margin-top: 20px;
}

.description h4 {
  margin-bottom: 10px;
  color: #303133;
}

.description p {
  line-height: 1.6;
  color: #606266;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  align-items: center;
}

.action-buttons .el-button {
  margin: 0;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

@media (max-width: 768px) {
  .listings-page {
    padding: 15px;
  }

  .el-table {
    font-size: 12px;
  }

  .el-pagination {
    text-align: center;
  }

  .el-dialog {
    width: 95% !important;
  }

  .action-buttons {
    gap: 4px;
  }

  .action-buttons .el-button {
    font-size: 11px;
    padding: 4px 8px;
  }
}

.phone-number {
  color: #606266;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
}

.no-phone {
  color: #C0C4CC;
  font-style: italic;
  font-size: 12px;
}
</style>
